<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="快递公司" prop="expressCompany">
        <el-input
          v-model="queryParams.expressCompany"
          placeholder="请输入快递公司"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="快递单号" prop="expressNo">
        <el-input
          v-model="queryParams.expressNo"
          placeholder="请输入快递单号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['point:logistics:add']"
        >新增物流</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['point:logistics:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['point:logistics:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['point:logistics:export']"
        >导出</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="el-icon-refresh"
          size="mini"
          @click="forceRefresh"
        >强制刷新</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!-- 重新设计的表格显示 -->
    <el-table v-loading="loading" :data="logisticsList" @selection-change="handleSelectionChange" key="logisticsTable">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="物流ID" align="center" prop="id" />
      <el-table-column label="订单编号" align="center">
        <template slot-scope="scope">
          {{ scope.row.exchangeOrder && scope.row.exchangeOrder.orderSn || '-' }}
        </template>
      </el-table-column>
      <el-table-column label="快递公司" align="center" prop="expressCompany" />
      <el-table-column label="快递单号" align="center" prop="expressNo" />
      <el-table-column label="物流状态" align="center" prop="status">
        <template slot-scope="scope">
          <el-tag :type="getLogisticsStatusType(scope.row.status)">
            {{ getLogisticsStatusText(scope.row.status) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="收货地址" align="center">
        <template slot-scope="scope">
          {{ scope.row.exchangeOrder && scope.row.exchangeOrder.userAddress && scope.row.exchangeOrder.userAddress.address || '-' }}
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['point:logistics:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['point:logistics:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 重新设计的新增物流信息对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="订单编号" prop="orderId">
          <el-select 
            v-model="form.orderId" 
            placeholder="请选择订单编号" 
            filterable 
            clearable
            @change="handleOrderChange"
            style="width: 100%"
          >
            <el-option
              v-for="order in processingOrders"
              :key="order.id"
              :label="`${order.orderSn} - ${(order.mallGoods && order.mallGoods.name) || '商品'}`"
              :value="order.id"
            >
              <span style="float: left">{{ order.orderSn }}</span>
              <span style="float: right; color: #8492a6; font-size: 13px">
                {{ (order.mallGoods && order.mallGoods.name) || '商品' }}
              </span>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="快递公司" prop="expressCompany">
          <el-input v-model="form.expressCompany" placeholder="请输入快递公司" />
        </el-form-item>
        <el-form-item label="快递单号" prop="expressNo">
          <el-input v-model="form.expressNo" placeholder="请输入快递单号" />
        </el-form-item>
        <el-form-item label="收货地址" prop="address">
          <el-input v-model="selectedOrderAddress" placeholder="收货地址" disabled />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="info" @click="debugFormData">调试数据</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listLogistics, getLogistics, delLogistics, addLogistics, updateLogistics } from "@/api/point/logistics"
import request from "@/utils/request"

export default {
  name: "Logistics",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 物流信息表格数据
      logisticsList: [],
      // 处理中订单列表（用于下拉选择）
      processingOrders: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        expressCompany: null,
        expressNo: null,
      },
      // 表单参数
      form: {},
      // 选中的订单地址
      selectedOrderAddress: "",
      // 表单校验
      rules: {
        orderId: [
          { required: true, message: "订单编号不能为空", trigger: "change" }
        ],
        expressCompany: [
          { required: true, message: "快递公司不能为空", trigger: "blur" }
        ],
        expressNo: [
          { required: true, message: "快递单号不能为空", trigger: "blur" }
        ]
      }
    }
  },
  created() {
    this.getList()
    this.getProcessingOrders()
  },
  methods: {
    /** 查询物流信息列表 - 使用新的多表联查接口 */
    getList() {
      this.loading = true
      console.log('=== 开始获取物流列表 ===')
      
      request({
        url: '/point/logistics/list-with-order',
        method: 'get',
        params: this.queryParams
      }).then(response => {
        console.log('获取到的物流响应:', response)
        
        if (response.code === 200) {
          this.logisticsList = response.rows || []
          this.total = response.total || 0
          console.log('物流列表数据:', this.logisticsList)
        } else {
          this.$modal.msgError(response.msg || "获取物流数据失败")
        }
        this.loading = false
      }).catch(error => {
        console.error('获取物流数据失败:', error)
        this.$modal.msgError("获取物流数据失败")
        this.loading = false
      })
    },

    /** 获取处理中的订单列表 */
    getProcessingOrders() {
      console.log('=== 开始获取处理中订单 ===')
      
      request({
        url: '/point/logistics/processing-orders',
        method: 'get'
      }).then(response => {
        console.log('获取到的处理中订单响应:', response)
        
        if (response.code === 200) {
          this.processingOrders = response.data || []
          console.log('处理中订单列表:', this.processingOrders)
        } else {
          console.error('获取处理中订单失败:', response.msg)
        }
      }).catch(error => {
        console.error('获取处理中订单失败:', error)
      })
    },

    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },

    // 表单重置
    reset() {
      this.form = {
        id: null,
        orderId: null,
        expressCompany: null,
        expressNo: null,
        status: null,
        createTime: null,
        del: 0
      }
      this.selectedOrderAddress = ""
    },

    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },

    /** 重置按钮操作 */
    resetQuery() {
      this.queryParams = {
        pageNum: 1,
        pageSize: 10,
        expressCompany: null,
        expressNo: null,
      }
      this.handleQuery()
    },

    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },

    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.getProcessingOrders() // 重新获取处理中订单
      this.open = true
      this.title = "新增物流信息"
    },

    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const id = row.id || this.ids
      
      request({
        url: `/point/logistics/${id}`,
        method: 'get'
      }).then(response => {
        if (response.code === 200) {
          this.form = response.data
          this.open = true
          this.title = "修改物流信息"
        } else {
          this.$modal.msgError(response.msg || "获取物流详情失败")
        }
      }).catch(error => {
        console.error('获取物流详情失败:', error)
        this.$modal.msgError("获取物流详情失败")
      })
    },

    /** 订单选择变化处理 */
    handleOrderChange(orderId) {
      console.log('选择的订单ID:', orderId)
      
      if (orderId) {
        const selectedOrder = this.processingOrders.find(order => order.id === orderId)
        if (selectedOrder && selectedOrder.userAddress) {
          this.selectedOrderAddress = selectedOrder.userAddress.address
          console.log('选中的订单地址:', this.selectedOrderAddress)
        } else {
          this.selectedOrderAddress = "地址信息不完整"
        }
      } else {
        this.selectedOrderAddress = ""
      }
    },

    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            // 修改操作
            console.log('提交修改的表单数据:', this.form)
            
            updateLogistics(this.form).then(response => {
              if (response.code === 200) {
                this.$modal.msgSuccess("修改成功")
                this.open = false
                this.getList()
              } else {
                this.$modal.msgError(response.msg || "修改失败")
              }
            }).catch(error => {
              console.error('修改失败:', error)
              this.$modal.msgError("修改失败")
            })
          } else {
            // 新增操作 - 使用新的接口
            console.log('提交新增的表单数据:', this.form)
            
            request({
              url: '/point/logistics/add-and-update-order',
              method: 'post',
              data: this.form
            }).then(response => {
              console.log('新增物流响应:', response)
              
              if (response.code === 200) {
                this.$modal.msgSuccess("新增成功，订单状态已更新为已发货")
                this.open = false
                this.getList()
                this.getProcessingOrders() // 刷新处理中订单列表
              } else {
                this.$modal.msgError(response.msg || "新增失败")
              }
            }).catch(error => {
              console.error('新增失败:', error)
              this.$modal.msgError("新增失败")
            })
          }
        }
      })
    },

    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids
      this.$modal.confirm('是否确认删除物流信息编号为"' + ids + '"的数据项？').then(function() {
        return delLogistics(ids)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess("删除成功")
      }).catch(() => {})
    },

    /** 导出按钮操作 */
    handleExport() {
      this.download('point/logistics/export', {
        ...this.queryParams
      }, `logistics_${new Date().getTime()}.xlsx`)
    },

    // 强制刷新数据
    forceRefresh() {
      console.log('=== 手动强制刷新 ===')
      this.getList()
      this.getProcessingOrders()
    },

    // 获取物流状态类型
    getLogisticsStatusType(status) {
      if (status === 0) {
        return 'info'      // 已兑换：蓝色
      } else if (status === 1) {
        return 'success'   // 已发货：绿色
      } else if (status === 2) {
        return 'warning'   // 已签收：橙色
      }
      return ''
    },

    // 获取物流状态文本
    getLogisticsStatusText(status) {
      if (status === 0) {
        return '已兑换'
      } else if (status === 1) {
        return '已发货'
      } else if (status === 2) {
        return '已签收'
      }
      return ''
    },

    // 调试表单数据
    debugFormData() {
      console.log('当前表单数据:', this.form)
      console.log('处理中订单列表:', this.processingOrders)
      console.log('选中的订单地址:', this.selectedOrderAddress)
      this.$modal.msgSuccess('当前表单数据已打印到控制台')
    }
  }
}
</script>
